from fastapi import APIRouter
from pydantic import BaseModel
from typing import List, Dict, Any, Optional

router = APIRouter()

class QueryModel(BaseModel):
    question: str
    user_id: str

class RecommendationModel(BaseModel):
    user_id: str
    subject: str

class DocumentProcessModel(BaseModel):
    file_path: str
    file_type: str  # "text" or "pdf"
    use_mineru_pages: Optional[List[int]] = None

class ProgressUpdateModel(BaseModel):
    user_id: str
    subject: str
    progress: float  # 0-1之间的数值

@router.get("/")
async def root():
    return {"message": "欢迎使用AI教育助手"}

@router.post("/query")
async def query_knowledge(query: QueryModel):
    """处理知识问答请求"""
    # 检查短期缓存中是否有相关回答
    from app.core.cache import cache_manager
    cached_answer = cache_manager.get_short_term_cache(f"qa:{query.user_id}:{query.question}")
    if cached_answer:
        return cached_answer
    
    # 生成新的回答
    from app.core.qa_system import qa_chain_system
    answer = qa_chain_system.answer_question(query.question, query.user_id)
    
    # 缓存回答（短期）
    cache_manager.set_short_term_cache(f"qa:{query.user_id}:{query.question}", answer)
    
    return answer

@router.post("/recommend")
async def recommend_learning_path(recommendation: RecommendationModel):
    """生成个性化学习路径推荐"""
    from app.core.recommendation import recommendation_system
    learning_path = recommendation_system.generate_learning_path(
        recommendation.user_id, 
        recommendation.subject
    )
    
    return {
        "user_id": recommendation.user_id, 
        "subject": recommendation.subject,
        "learning_path": learning_path
    }

@router.post("/process_document")
async def process_document(doc_info: DocumentProcessModel):
    """处理文档"""
    from app.utils.document_processor import DocumentProcessor
    
    processor = DocumentProcessor()
    
    if doc_info.file_type == "text":
        content = processor.process_text_document(doc_info.file_path)
        return {"content": content, "type": "text"}
    elif doc_info.file_type == "pdf":
        result = processor.process_pdf_document(
            doc_info.file_path, 
            doc_info.use_mineru_pages
        )
        return result
    else:
        return {"error": "不支持的文件类型"}

@router.post("/update_progress")
async def update_progress(progress_info: ProgressUpdateModel):
    """更新学习进度"""
    from app.core.recommendation import recommendation_system
    success = recommendation_system.update_user_progress(
        progress_info.user_id,
        progress_info.subject,
        progress_info.progress
    )
    
    return {
        "user_id": progress_info.user_id,
        "subject": progress_info.subject,
        "success": success
    }

@router.get("/user_profile/{user_id}")
async def get_user_profile(user_id: str):
    """获取用户画像"""
    from app.core.recommendation import recommendation_system
    profile = recommendation_system.analyze_user_profile(user_id)
    return profile
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn

from app.core.config import settings
from app.api.routes import router as api_router

app = FastAPI(
    title="AI教育助手",
    description="集知识问答、个性化学习路径推荐于一体的AI教育助手",
    version="1.0.0"
)

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 创建uploads目录用于存储上传的文件（如果不存在）
import os
if not os.path.exists("uploads"):
    os.makedirs("uploads")

# 挂载上传文件目录
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")

# 配置模板
templates = Jinja2Templates(directory="templates")

# 添加文档上传页面路由
@app.get("/document_upload", response_class=HTMLResponse)
async def document_upload_page(request: Request):
    return templates.TemplateResponse("document_upload.html", {"request": request})

# 包含API路由
app.include_router(api_router, prefix="/api")

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

# 为了方便测试，添加一个简单的测试端点
@app.get("/test")
async def test_endpoint():
    return {"message": "服务器运行正常"}

if __name__ == "__main__":
    uvicorn.run(app, host="localhost", port=settings.APP_PORT)